﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using DrillingTrack3D.controller;
using DrillingTrack3D.Model;
using DrillingTrack3D.Utils;

namespace DrillingTrack3D.Coordinates.controller
{
    /// <summary>
    /// DrillingDataController 的摘要说明
    /// </summary>
    public class DrillingDataController : Ajax
    {
        public void GetHoleData()
        {
            var holeIds = Request.QueryString["holeId[]"];

            var path = Request.QueryString["Path"];

            if (path == "shendu")
            {
                path = "深度";
            }
            else if (path == "jiaodu")
            {
                path = "角度";
            }
            if (holeIds == null)
            {
                holeIds = Request.Form["holeIds[]"];
            }
            if(holeIds == null)return;

            var listHoleId = holeIds.Split(',');

            var result = new Dictionary<string, List<XYZModel>>();
            if (listHoleId.Any())
            {
                foreach (var holeId in listHoleId)
                {
                    var list = new List<XYZModel>();
                    string fileName = string.Format("{0}Data\\{2}\\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, holeId,path);

                    using (var sr = new StreamReader(fileName, Encoding.Default))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                        {
                            string[] model = s.Split('^');

                            if (path == "深度")
                            {
                                list.Add(new XYZModel(model[0].Trim(), model[1].Trim(), model[2].Trim(), model[3].Trim(), model[4].Trim(), model[5].Trim(), model[6].Trim()));
                            }
                            else
                            {
                                list.Add(new XYZModel(model[0].Trim(), model[1].Trim(), model[2].Trim(), model[3].Trim(), model[4].Trim(), model[5].Trim()
                              , model[6].Trim(), model[7].Trim(), model[8].Trim()));
                            }
                        }
                        sr.Close();
                    }
                    result.Add(holeId, list);
                }
            }

            OutputString = JsonUtil.ToJson(result);
        }

        public void GetHoleIds()
        {
            OutputString = string.Empty;
            var path = Request.QueryString["Path"];
            if (Request.QueryString["pageSize"] == null) return;

            if (path == "shendu")
            {
                path = "深度";
            }
            else if (path == "jiaodu")
            {
                path = "角度";
            }

            var pageSize = int.Parse(Request.QueryString["pageSize"]);
            var pageNum = int.Parse(Request.QueryString["pageNum"]);
            var searchTerm = Request.QueryString["searchTerm"];
            var callback = Request.QueryString["callback"];

            var files = new string[0];
            string cacheKey = "holeIds";
            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                files = (string[]) HttpContext.Current.Cache[cacheKey];
            }
            else
            {
                var rootPath = Server.MapPath(string.Format("~\\Data\\{0}",path));

                files = Directory.GetFiles(rootPath);
                HttpContext.Current.Cache[cacheKey] = files;
            }

            var group = files.Select(o => new { createTime = File.GetCreationTime(o).ToString("yyyy-MM-dd"), fileName = Path.GetFileNameWithoutExtension(o) })
                .GroupBy(o=>o.createTime)
                .OrderByDescending(o=>o.Key);

            var page = group 
                .Skip(pageSize * (pageNum - 1))
                .Take(pageSize);

            var pagedResult = new Select2PagedResult
            {
                Total = group.Count(),
                Results = page.Select(o => new Select2Group
                {
                    Group = o.Key,
                    Options = o.Select(t => new Select2Result
                    {
                        id = t.fileName,
                        text = t.fileName
                    }).ToList()
                }).ToList(),
            };

            WriteCallback(HttpContext.Current, JsonUtil.ToJson(pagedResult));
        }

        private void WriteCallback(HttpContext context, string json)
        {
            context.Response.Write(string.Format("{0}('{1}');", context.Request["callback"], json));
        }
    }

    public class Select2PagedResult
    {
        public int Total { get; set; }

        public List<Select2Group> Results { get; set; }
    }

    public class Select2Group
    {
        public string Group { get; set; }

        public List<Select2Result> Options { get; set; }
    }

    public class Select2Result
    {
        public string id { get; set; }
        public string text { get; set; }
    }
}